package cn.springcloud.api.apiUtils;


import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String 工具类
 *
 */
public class StringUtil {

    private static Pattern linePattern = Pattern.compile("_(\\w)");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    private final static Pattern p = Pattern.compile("\\d+");

    private final  static  String  ZFSTR = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM" ;
    private final  static  String  numberSTR = "0123456789" ;

    /**
     * 下划线转驼峰
     *
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        if (null == str || "".equals(str)) {
            return str;
        }
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);

        str = sb.toString();
        str = str.substring(0, 1).toUpperCase() + str.substring(1);

        return str;
    }

    /**
     * 驼峰转下划线,效率比上面高
     *
     * @param str
     * @return
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线(简单写法，效率低于{@link #humpToLine(String)})
     *
     * @param str
     * @return
     */
    public static String humpToLine2(String str) {
        return str.replaceAll("[A-Z]", "_$0").toLowerCase();
    }

    /**
     * 首字母转小写
     *
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s) {
        if (StringUtils.isBlank(s)) {
            return s;
        }
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return String.valueOf(Character.toLowerCase(s.charAt(0))) + s.substring(1);
        }
    }

    /**
     * 首字母转大写
     *
     * @param s
     * @return
     */
    public static String toUpperCaseFirstOne(String s) {
        if (StringUtils.isBlank(s)) {
            return s;
        }
        if (Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return String.valueOf(Character.toUpperCase(s.charAt(0))) + s.substring(1);
        }
    }

    /**
     * object转String
     *
     * @param object
     * @return
     */
    public static String getString(Object object) {
        return getString(object, "");
    }

    public static String getString(Object object, String defaultValue) {
        if (null == object) {
            return defaultValue;
        }
        try {
            return object.toString();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * object转Integer
     *
     * @param object
     * @return
     */
    public static int getInt(Object object) {
        return getInt(object, -1);
    }

    public static int getInt(Object object, Integer defaultValue) {
        if (null == object) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * object转Boolean
     *
     * @param object
     * @return
     */
    public static boolean getBoolean(Object object) {
        return getBoolean(object, false);
    }

    public static boolean getBoolean(Object object, Boolean defaultValue) {
        if (null == object) {
            return defaultValue;
        }
        try {
            return Boolean.parseBoolean(object.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 使用正则提取字符串
     * 参考：http://pure.iteye.com/blog/544403
     *
     * @param regex
     * @param source
     * @return
     */
    public static String getMatcher(String regex, String source) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            //只取第一组
            result = matcher.group(1);
        }
        return result;
    }

    public static boolean containsAny(String script, String... strs) {
        for (String str : strs) {
            if (script.contains(str)) {
                return true;
            }
        }
        return false;
    }


    public static String firstNum(String s) {
        Matcher m = p.matcher(s);

        return m.find() ? m.group() : null;
    }

    /**
     * 是否未定义
     *
     * @param cellValue
     * @return
     */
    public static boolean isUndefined(String cellValue) {
        return "undefined".equals(cellValue) || "null".equals(cellValue) || "".equals(cellValue);
    }

    /**
     * 不为空
     *
     * @param str
     * @return
     */
    public static boolean isNotBlank(String str) {
        return str != null && str.length() > 0 && str.trim().length() > 0;
    }

    /**
     * 清除干扰符号
     */
    public static String cleanDisturbSymbol(String str) {
        if (StringUtils.isNotBlank(str)) {
            String regex = "[`~!@#$%^&*()_\\-+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？☆ \\t]";
            return str.replaceAll(regex, "").trim();
        }

        return "";
    }

    /**
     * 是否包含中文字符
     */
    public static boolean containChinese(String str) {
        str = cleanDisturbSymbol(str);

        if (StringUtils.isNotBlank(str)) {
            for (char c : str.toCharArray()) {
                if (c >= 0x4E00 && c <= 0x9FA5) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取指定字符串出现的次数
     * 版权声明：本文为CSDN博主「麦田」的原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接及本声明。
     * 原文链接：https://blog.csdn.net/itmyhome1990/article/details/50855668
     *
     * @param srcText  源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    /**
     * 根据逗号或者回车分隔字符串
     */
    public static List<String> splitCommaOrEnter(String str) {
        List<String> res = new ArrayList<>();
        if (StringUtils.isNotBlank(str)) {
            for (String s : str.split(",")) {
                res.addAll(Lists.newArrayList(s.split("\n")));
            }
        }
        return res;

    }



    /**
     *  获得随机值
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        if(length<=0){
            length = 10 ;
        }
        HashSet<String> strSet = new HashSet<>(length);
        while(strSet.size()<length){
            strSet.add(String.valueOf(ZFSTR.charAt(new Random().nextInt(ZFSTR.length()))));
         }
        return Joiner.on("").join(strSet);
    }





}
